<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { type IGetJobData } from "@/api/job/types/job"
// import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { type FormInstance, ElMessage, ElNotification } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight, UploadFilled, Folder, Download } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { getToken } from "@/utils/cache/cookies"
import { formatDateTime } from "@/utils"
import { getSettleList, yongjinjiesuandown } from "@/api/yunShang"
defineOptions({
  name: "XcxYsSettle"
})

const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const uploadheaders = ref<any>({
  token: getToken()
})
//#region 增
const dialogVisible = ref<boolean>(false)

//#region 查
const tableData = ref<IGetJobData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  id: "",
  status: "",
  createTime: ""
})
// ****************excel批量上传*******************************
import { genFileId } from "element-plus"
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus"

const upload = ref<UploadInstance>()

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const handleSucc = (res: any) => {
  // console.log(res, "aaaa")
  if (res.data.duplicateList.length) {
    ElNotification({
      title: "存在重复订单",
      dangerouslyUseHTMLString: true,
      message: `<p>${res.data.duplicateList.join("<br/>")}</p>`,
      type: "warning",
      duration: 0
    })
  } else {
    ElMessage.success("上传成功！")
  }
  getTableData()
  // loading.value = false
}

const submitUpload = () => {
  // loading.value = true
  upload.value!.submit()
}
// *********************上传结束*************************

const getTableData = () => {
  getSettleList({
    start: new Date(searchData.createTime[0]).getTime() || "", // 时间
    end: new Date(searchData.createTime[1]).getTime() || "", // 时间
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    reName: searchData.name || "",
    id: searchData.id || "",
    status: searchData.status || ""
    // phone: searchData.phone || undefined
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
      loading.value = false
      // ElMessage.success("success")
    })
    .catch(() => {
      tableData.value = []
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// ** 清除规则报错信息
// const clearValidate = () => {
//   formRef.value?.clearValidate()
// }

//时间
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
import { shortcuts } from "@/utils/dateSet"
/** 订单下载 默认下载所有数据，查询后下载所有符合查询条件的数据*/
const downLoad = async () => {
  loading.value = true
  await yongjinjiesuandown({
    start: new Date(searchData.createTime[0]).getTime() || "", // 时间
    end: new Date(searchData.createTime[1]).getTime() || "", // 时间
    reName: searchData.name || "",
    id: searchData.id || "",
    status: searchData.status || ""
  }).then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "佣金结算列表.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
    loading.value = false
    // console.log(blob, 88888888)
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="createTime" label="订单日期">
          <el-date-picker
            v-model="searchData.createTime"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item prop="name" label="代理">
          <el-input v-model.trim="searchData.name" placeholder="请输入代理名" />
        </el-form-item>
        <el-form-item prop="status" label="结算状态">
          <el-select v-model="searchData.status" clearable filterable placeholder="请选择结算状态" style="width: 100%">
            <el-option :key="1" label="可结算" value="可结算" />
            <el-option :key="2" label="不可结算" value="不可结算" />
          </el-select>
        </el-form-item>
        <el-form-item prop="id" label="订单ID">
          <el-input v-model.trim="searchData.id" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true" style="display: none"
            >添加记录</el-button
          >
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
          <el-upload
            ref="upload"
            class="upload-demo"
            action="api/yun/balance/batchUpload"
            :limit="1"
            :headers="uploadheaders"
            :on-exceed="handleExceed"
            :on-success="handleSucc"
            :auto-upload="false"
            accept=".xlsx"
            style="display: inline-block; vertical-align: top; margin-left: 10px"
          >
            <template #trigger>
              <el-button type="danger" :icon="Folder">选择文件</el-button>
            </template>
            <el-button
              style="vertical-align: top"
              class="ml-3"
              type="success"
              :icon="UploadFilled"
              @click="submitUpload"
            >
              批量上传
            </el-button>
            <el-link
              type="primary"
              :icon="Download"
              style="margin-left: 50px"
              href="api/yun/balance/downTemplate"
              Download
              >下载模版</el-link
            >
          </el-upload>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="accountTime" label="账期时间" align="center">
            <template #default="scope">
              <span v-if="scope.row.accountTime !== null"> {{ formatDateTime(scope.row.accountTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="id" label="订单ID" align="center" />
          <el-table-column prop="createTime" label="结算单上传时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="结算状态" align="center" />
          <el-table-column prop="money" label="可结算金额" align="center" />
          <el-table-column prop="re_super_money" label="上级金额" align="center" />
          <el-table-column prop="re_upup_money" label="上上级金额" align="center" />
          <el-table-column prop="reName" label="代理账号" align="center" />
          <el-table-column prop="super_name" label="上级名称" align="center" />
          <el-table-column prop="upup_name" label="上上级名称" align="center" />
          <el-table-column prop="note" label="备注" align="center" />
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <!-- <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="60%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="名称">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" @close="restImg">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog> -->
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.block {
  padding: 30px 0;
  text-align: center;
  box-sizing: border-box;
  vertical-align: top;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
